import Mn from 'backbone.marionette';
import ModalFormBehavior from '../../base/behaviors/ModalFormBehavior.js';
import DateWidget from '../../widgets/DateWidget.js';
import InputWidget from '../../widgets/InputWidget.js';
import SelectWidget from '../../widgets/SelectWidget.js';
import Select2Widget from '../../widgets/Select2Widget.js';
import SelectBusinessWidget from '../../widgets/SelectBusinessWidget.js';
import Radio from 'backbone.radio';
import {
    hideLoader,
    showLoader
} from "../../tools";
import CheckboxWidget from "../../widgets/CheckboxWidget";


const ExpenseKmFormView = Mn.View.extend({
    behaviors: [ModalFormBehavior],
    template: require('./templates/ExpenseKmFormView.mustache'),
    id: "expensekm-form-popup-modal",
    regions: {
        'category': '.category',
        'date': '.date',
        'type_id': '.type_id',
        'start': '.start',
        'end': '.end',
        'km': '.km',
        'create_return': '.create_return',
        'description': '.description',
        'business_link': '.business_link',
    },
    ui: {
        modalbody: ".modal_content_layout",
    },
    // Bubble up child view events
    //
    childViewTriggers: {
        'change': 'data:modified',
        'finish': 'data:modified',
    },
    childViewEvents: {
        'finish': 'onChildChange',
    },
    onBeforeSync: showLoader,
    onFormSubmitted: hideLoader,

    initialize() {
        var channel = Radio.channel('config');
        this.type_options = channel.request(
            'get:options',
            'expensekm_types',
        );
        this.today = channel.request(
            'get:options',
            'today',
        );
        this.customers_url = channel.request(
            'get:options',
            'company_customers_url',
        );
        this.projects_url = channel.request(
            'get:options',
            'company_projects_url',
        );
        this.businesses_url = channel.request(
            'get:options',
            'company_businesses_url',
        );
    },
    showCategorySelect() {
        const view = new SelectWidget({
            options: [{
                'value': 1,
                'label': "Frais généraux"
            }, {
                'value': 2,
                'label': "Achats clients"
            }],
            title: "Catégorie",
            field_name: "category",
            value: this.model.get('category'),
        });
        this.showChildView('category', view);
    },
    refreshForm() {
        let view;

        if (!this.add) {
            this.showCategorySelect();
        }

        view = new DateWidget({
            date: this.model.get('date'),
            title: "Date",
            field_name: "date",
            current_year: true,
            default_value: this.today,
            required: true,
        });
        this.showChildView("date", view);

        view = new Select2Widget({
            value: this.model.get('type_id'),
            title: 'Type de dépense',
            field_name: 'type_id',
            field_id: 'type_id',  // Nécessaire pour pouvoir résoudre le bug de nav au clavier
            options: this.type_options,
            id_key: 'id',
            required: true,
        });
        this.showChildView('type_id', view);

        view = new InputWidget({
            value: this.model.get('start'),
            title: 'Point de départ',
            field_name: 'start',
            required: true,
        });
        this.showChildView('start', view);

        view = new InputWidget({
            value: this.model.get('end'),
            title: "Point d'arrivée",
            field_name: 'end',
            required: true,
        });
        this.showChildView('end', view);

        view = new InputWidget({
            value: this.model.get('km'),
            title: "Nombre de kilomètres",
            field_name: 'km',
            addon: "km",
            required: true,
        });
        this.showChildView('km', view);

        view = new CheckboxWidget({
            value: this.model.get('create_return'),
            inline_label: "Créer un trajet retour",
            field_name: 'create_return',
            description: (
                "Créer une seconde ligne de frais pour le " +
                "trajet retour, avec le même kilométrage."
            ),
        });
        this.showChildView('create_return', view);

        view = new InputWidget({
            value: this.model.get('description'),
            title: 'Motif de déplacement',
            field_name: 'description'
        });
        this.showChildView('description', view);

        if (this.model.get('category') != 1) {
            view = new SelectBusinessWidget({
                title: 'Rattacher la dépense à',
                customers_url: this.customers_url,
                projects_url: this.projects_url,
                businesses_url: this.businesses_url,
                customer_value: this.model.get('customer_id'),
                project_value: this.model.get('project_id'),
                business_value: this.model.get('business_id'),
                customer_label: this.model.get('customer_label'),
                project_label: this.model.get('project_label'),
                business_label: this.model.get('business_label'),
                required: false,
            });
            this.showChildView('business_link', view);
        }
    },
    afterSerializeForm(datas) {
        let modifiedDatas = _.clone(datas);

        /* We also want the category to be pushed to server,
         * even if not present as form field
         */
        modifiedDatas['category'] = this.model.get('category');

        // Hack to allow setting those fields to null.
        // Otherwise $.serializeForm skips <select> with no value selected
        modifiedDatas['customer_id'] = this.model.get('customer_id');
        modifiedDatas['project_id'] = this.model.get('project_id');
        modifiedDatas['business_id'] = this.model.get('business_id');

        return modifiedDatas;
    },
    templateContext: function () {
        return {
            title: this.getOption('title'),
            button_title: this.getOption('buttonTitle'),
        };
    },
    onRender() {
        this.refreshForm();
    },
    onSuccessSync() {
        const create_return = this.model.get("create_return");
        if (create_return && create_return != '0') {
            // instantiate a second line correspondind to the return journey
            Radio.channel("facade").request("create:return_expense_kmline", this.model);
        } else if (this.add) {
            var this_ = this;
            var modalbody = this.getUI('modalbody');

            modalbody.effect(
                'highlight', {
                    color: 'rgba(0,0,0,0)'
                },
                800,
                this_.refresh.bind(this)
            );
            modalbody.addClass('action_feedback success');
        } else {
            this.triggerMethod('modal:close');
        }
    },
    onModalBeforeClose() {
        this.model.rollback();
    },
});
export default ExpenseKmFormView;